package model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import controller.ConfigController;

public class MacroList implements Iterable<Macro>, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 760066748904298810L;

	private static MacroList instance;

	private MacroList() {
	}

	public static MacroList getInstance() {
		if (instance == null) {
			load();
		}
		return instance;
	}

	private Collection<Macro> macro;

	public Collection<Macro> getMacro() {
		return macro;
	}

	public void setMacro(Collection<Macro> macro) {
		this.macro = macro;
	}

	public void addMacro(Macro macro) {
		getMacro().add(macro);
	}

	private static MinCommandSet minCommandSet;

	public void store() {
		File file = new File(minCommandSet.getName() + ".macro");
		try {
			ObjectOutputStream out = new ObjectOutputStream(
					new FileOutputStream(file));
			out.writeObject(getInstance());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void removeMacro(String macroName) {
		ArrayList<Macro> list = new ArrayList<Macro>();
		for (Macro macro : getMacro()) {
			if (!macro.getName().trim().equals(macroName.trim())) {
				list.add(macro);
			}
		}
		setMacro(list);
	}

	private static void load() {
		minCommandSet = ConfigController.getInstance().getMinCommandSet();
		File file = new File(minCommandSet.getName() + ".macro");
		instance = new MacroList();
		if (file.canRead() && file.exists()) {
			try {
				ObjectInputStream in = new ObjectInputStream(
						new FileInputStream(file));
				instance = (MacroList) in.readObject();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			instance.setMacro(new ArrayList<Macro>());
		}
	}

	@Override
	public Iterator<Macro> iterator() {
		if (macro == null) {
			return null;
		}
		return macro.iterator();
	}
}
